package com.stuManager.servlet;

import com.alibaba.fastjson.JSON;
import com.stuManager.model.CommonResponseModel;
import com.stuManager.model.Student;
import com.stuManager.service.StudentService;
import com.stuManager.util.CookiesUtil;
import com.stuManager.util.ReadPostBodyUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/*
    DeleteStudentServlet
    删除学生信息接口
 */
@WebServlet(name = "DeleteStudentServlet", value = "/deleteStudent")
public class DeleteStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //处理删除学生的请求
        Cookie token = CookiesUtil.getCookieByName(request, "token");
        CommonResponseModel m = new CommonResponseModel();
        if (token == null) {
            m.setErrorCode(1);
            m.setMessage("用户未授权");
        }
        else {
            //获取一个service来处理业务
            StudentService service = new StudentService();
            //获取post参数。
            String requestBody = ReadPostBodyUtil.getPostData(request);
            Student student = JSON.parseObject(requestBody, Student.class);
            m = service.requestDeleteStudent(student, token.getValue());
        }
        String jsonString = JSON.toJSONString(m);
        System.out.println("返回字符串:\n" + jsonString);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(jsonString);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
